package com.itheima.Task;

import com.itheima.common.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class ImageCleanupTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Scheduled(cron = "0 0 0 1/7 * ? ") // 每隔7天执行一次
    public void cleanupImages() {
        // 获取 uploaded_images 集合
        Set<String> uploadedImages = redisTemplate.opsForSet().members("uploaded_images");
        // 获取 used_images 集合
        Set<String> usedImages = redisTemplate.opsForSet().members("used_images");

        if (uploadedImages != null && usedImages != null) {
            // 计算差值
            uploadedImages.removeAll(usedImages);

            for (String imageName : uploadedImages) {
                // 从 OSS 中删除图片
                aliOssUtil.delete(imageName);
                // 从 Redis 中删除记录
                redisTemplate.opsForSet().remove("uploaded_images", imageName);
            }
        }
    }
}
